// pages/stationModify/stationModify.js
const app  = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgs: [],
    items: [{
      name: "特色服务"
      },
      {
        name: "支持使用加油物资单"
      }
    ],
    img_l: '',
    startX: 0, //开始坐标
    startY: 0,
    showModal: false,
    LabelNew: '',
    TipsNew:'',
    LabelItems: [
    ],//推广标签
    extension_tag_ids:[],
    pid:'',//上级id
    data:{},//店铺信息
    num: 1,
    address: "标注后有利于引导客源",
    dayItems:[
      { 'data_Item': '周一', "state": 0 },
      { 'data_Item': '周二', "state": 0 },
      { 'data_Item': '周三', "state": 0 },
      { 'data_Item': '周四', "state": 0 },
      { 'data_Item': '周五', "state": 0 },
      { 'data_Item': '周六', "state": 0 },
      { 'data_Item': '周日', "state": 0 },
    ],
    hiddens: false,// 地图选点
    hiddenYuLan:true,//预览
    ishidden:false,//
    xingJi: [],//酒店星级
    index:1,
    TipsItems:[
    ],
    time1: "08:00",
    time2: "18:00",
    region: [],
    regionId:[],
    province_id:'',
    city_id:'',
    area_id:'',
    longitude:'',
    latitude:"",
    desc:'',
    per_spend:'',
    hotel_level:'',
    decoration_time:'',
    service_phone:'',
    detail_address:'',
    near:'',
    business_hours:'',
    service:[],
    address:'',
  },
  operatingClick(){
    app.post("/merchant/operating","put",{}).then(res =>{
      wx.showToast({
        title: res.msg,
        duration:500
      })
      setTimeout(function(){
        wx.navigateBack({
          delta:1
        })
      },500)
    })
  },
  // 酒店星级
  bindPickerChange: function (e) {
    let that = this;
    
    that.setData({
      index: e.detail.value,
      hotel_level: that.data.xingJi[e.detail.value].name,
      ishidden: true
    })
    
  },
  getName(e){
    let that = this;
    that.setData({ desc: e.detail.value })
  },
  //描述
  getDesc(e){
    let that = this;
    that.setData({ desc:e.detail.value})
  },
  service_phone(e) {//客服电话
    let that = this;
    that.setData({ service_phone: e.detail.value })
  },
  service_price(e){//人均消费
    let that = this;
    that.setData({ per_spend: e.detail.value })
  },
  service_times(e) {//装修时间
    let that = this;
    that.setData({ decoration_time: e.detail.value })
  },
  getNear(e) {//附近
    let that = this;
    that.setData({ near: e.detail.value })
  },
  service_address(e) {//详细地址
    let that = this;
    that.setData({ detail_address: e.detail.value })
  },
  getTime(e) {//营业时间
    let that = this;
    that.setData({ business_hours	: e.detail.value })
  },
  

  // 预览关闭
  yuLanClick(){
    wx.navigateTo({
      url: '../preview/preview'
    })
  },
  //点击保存
  formSubmit: function (e) {
    console.log(e)
    let form = e.detail.value;
    var that = this;
    let psotData = {
      logo: that.data.img_l,
      merchant_type_id:that.data.pid,
      images: that.data.imgs,
      cover_image: that.data.imgs[0],
      desc: form.desc,
      per_spend: form.per_spend,
      hotel_level: that.data.hotel_level,
      extension_tag_ids: that.data.extension_tag_ids,
      service_phone: form.service_phone,
      province_id: that.data.regionId[0],
      city_id: that.data.regionId[1],
      area_id: that.data.regionId[2],
      detail_address: form.detail_address,
      near: form.near,
      lng: that.data.longitude,
      lat: that.data.latitude,
      business_hours: form.business_hours,
      service: that.data.TipsItems
    };
    app.post("/merchant/edit", "put", psotData).then(res =>{
      wx.showToast({
        title: res.msg,
        duration:1000
      });
      setTimeout(function(){
        wx.reLaunch({
          url: '../index/index'
        })
      },1000)
     
    })
    // wx.navigateTo({
    //   url: '../indexInActive3/indexInActive3'
    // })
  },
  bindRegionChange: function (e) {
    console.log('picker发送选择改变，携带值为', e)

    this.setData({
      region: e.detail.value,
      regionId: e.detail.code
    })
  },
  //点击推广标签
  select_item1: function (e) {
    let that = this;
    var index = e.currentTarget.dataset.key;
    
    if (that.data.LabelItems[index].state == 1) {
      that.data.LabelItems[index].state = 0;
      that.data.extension_tag_ids.splice(index, 1)
    } else if (that.data.LabelItems[index].state === 0) {
      var num = 0;
      that.data.extension_tag_ids.push(that.data.LabelItems[index].id)
      for (var i = 0; i < that.data.LabelItems.length; i++) {
        if (that.data.LabelItems[i].state === 1) {
          num++;
        }
      }
      if (num < 3) {
        that.data.LabelItems[index].state = 1;
      } else {
        wx.showToast({
          title: '最多可选择3个',
          icon: 'none',
          duration: 2000
        })
      }
    }
    this.setData({
      LabelItems: this.data.LabelItems
    });
  },
  selectDayitem:function(e){
    var index = e.currentTarget.dataset.key;
    if (this.data.dayItems[index].state == 1) {
      this.data.dayItems[index].state = 0;
    } else if (this.data.dayItems[index].state === 0) {
      this.data.dayItems[index].state = 1;
    }
    this.setData({
      dayItems: this.data.dayItems
    });
  },
  // 选择地图
  gomap1() {
    let that = this;
    that.setData({
      hiddens: false
    })
  },
  gomap: function (e) {
    let that = this;
    if (that.data.longitude){
      wx.showModal({
        title: '提示',
        content: '确认要修改标注吗？',
        success:function(res){
          if (res.cancel) {
            //点击取消,默认隐藏弹框
          } else {
            //点击确定
            that.setData({
              hiddens: !that.data.hiddens
            })
            that.moveToLocation();
          }
        }
      })
    }else{
      that.setData({
        hiddens: !that.data.hiddens
      })
      that.moveToLocation();
    }
    // that.setData({
    //   hiddens: !that.data.hiddens
    // })
    // that.moveToLocation();
    // wx.navigateTo({
    //   url: '../map/map'
    // })
  },
 
  //移动选点
  moveToLocation: function () {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        console.log(res);
        that.setData({ 
          latitude: res.latitude,
           longitude: res.longitude,
          address: res.name,
          data:{
            merchant:{
              detail_address:res.name
            }
          } })
        //选择地点之后返回到原来页面
        // wx.navigateTo({
        //   url: "/pages/index3/index3?address=" + res.name + "&num=2&latitude=" + res.latitude + "&longitude=" + res.longitude
        // });
      },
      fail: function (err) {
        wx.navigateTo({
          url: "/pages/stationModify1/stationModify1"
        })
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(e) {
    if (e.address != null && e.address != '' && e.num != null && e.num != '') {
      var that = this;
      common.sys_main(app, that, e);
      for (var i = 0; i < 10; i++) {
        this.data.TipsItems.push({
          content: i + "",
          isTouchMove: false
        })
      }
      this.setData({
        TipsItems: this.data.TipsItems
      });

    }
   
  },
  touchstart: function(e) {
    this.data.TipsItems.forEach(function(v, i) {
      if (v.isTouchMove)
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      TipsItems: this.data.TipsItems
    })
  },
  touchmove: function(e) {
    var that = this,
      index = e.currentTarget.dataset.index,
      startX = that.data.startX,
      startY = that.data.startY,
      touchMoveX = e.changedTouches[0].clientX,
      touchMoveY = e.changedTouches[0].clientY,
      //获取滑动角度

      angle = that.angle({
        X: startX,
        Y: startY
      }, {
        X: touchMoveX,
        Y: touchMoveY
      });
    that.data.TipsItems.forEach(function(v, i) {
      v.isTouchMove = false
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX)
          v.isTouchMove = false
        else
          v.isTouchMove = true
      }
    })
    that.setData({
      TipsItems: that.data.TipsItems
    })
  },
  angle: function(start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },
  del: function(e) {
    this.data.TipsItems.splice(e.currentTarget.dataset.index, 1)
    this.setData({
      TipsItems: this.data.TipsItems
    })
  },
  bindTimeChange1: function (e) {
    //设置事件
    this.setData({
      //给当前time进行赋值
      time1: e.detail.value
    })
  },
  bindTimeChange2: function (e) {
    //设置事件
    this.setData({
      //给当前time进行赋值
      time2: e.detail.value
    })
  },
  
  
  chooseImg2: function () {//调用
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      success: function (res) {
        var tempFilePaths = res.tempFilePaths;
        wx.uploadFile({
          url: 'https://api.51huijingang.com/api/merchant/upload', //仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name: "file",
          success: function (data) {
            var datas = JSON.parse(data.data);
            console.log(datas)
            var datass = datas.url
            that.setData({ img_l: datass })
          }
        })
      },
    })
  },
 
  chooseImg: function(e) {
    var that = this;
    var imgs = that.data.imgs;
    if (imgs.length >= 5) {
      that.setData({
        lenMore: 1
      });
      setTimeout(function() {
        that.setData({
          lenMore: 0
        });
      }, 2500);
      return false;
    }
    
    wx.chooseImage({
      // count: 1, // 默认9
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        var imgs = that.data.imgs;
        wx.uploadFile({
          url: 'https://api.51huijingang.com/api/merchant/upload', //仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name: "file",
          success: function (data) {
            var datas = JSON.parse(data.data);
            console.log(datas)
            var datass = datas.url;
            imgs.push(datass);
            that.setData({
              imgs: imgs
            });
          }
        })
          
        
       
        
       
      }
    });
  },
  deleteImg: function(e) {
    var imgs = this.data.imgs;
    var index = e.currentTarget.dataset.index;
    imgs.splice(index, 1);
    this.setData({
      imgs: imgs
    });
  },
  previewImg: function(e) {
    //获取当前图片的下标
    var index = e.currentTarget.dataset.index;
    //所有图片
    var imgs = this.data.imgs;
    wx.previewImage({
      //当前显示图片
      current: imgs[index],
      //所有图片
      urls: imgs
    })
  },
  DelLabel(e) {
   var id= e.currentTarget.id;
   let that= this;
    app.post("/merchant/del_tag","DELETE",{id:id}).then(res =>{
      wx.showToast({
        title: res.msg,
        duration:1000
      })
      that.tagList(that.data.pid)
    })
  },
  listenerNewLabelInput: function (e) {
    if (e.detail.value.length>=6){
      wx.showModal({
        title: '提示',
        content: '输入的标签长度不能超过6个字符',
      })
      return;
    }else{
      this.data.LabelNew = e.detail.value;
    }
    
  },
  // 点击添加标签
  AddLabel() {
    let that = this;
    if (!that.data.LabelNew){
      wx.showToast({
        title: '请输入添加的特色',
      })
      return;
    }
    if (that.data.LabelNew.length>6) {
      wx.showToast({
        title: '添加的特色的字符长度不能超过6个字符',
      })
      return;
    }
    app.post("/merchant/add_tag", "post", { pid: that.data.pid, name: that.data.LabelNew}).then(res =>{
      wx.showToast({
        title: res.msg,
        duration:1000
      })
      
      that.tagList(that.data.pid)
    })
    // let customLabel = this.data.LabelItems;
    // if (this.data.LabelNew != '') {
    //   var itemLabel = { 'data_Item': this.data.LabelNew, "state": 0 }
    //   customLabel.push(itemLabel);
    // }
    // // customLabel.splice(index, 1);
    // this.setData({
    //   LabelItems: customLabel
    // });
  },

  listenerNewTipsInput: function (e) {
    console.log(e)
    if(e.detail.value.length>=6){
      wx.showToast({
        title: '字符长度不能大于6位',
      });
      return;

    }else{
      this.data.TipsNew = e.detail.value;
    }
   
  },
  AddTips(e) {
    let that = this;
    let customLabel = that.data.TipsItems;
    console.log(that.data.TipsNew)
    if (that.data.TipsNew != '') {
      var itemLabel = { 'data_Item': that.data.TipsNew}
      customLabel.push(itemLabel);
    }
    
    // customLabel.splice(index, 1);
    that.setData({
      TipsItems: customLabel
    });
  },
  OpenModal: function (e) {
    this.setData({
      showModal: true
    })
  },
  closeModal: function (e) {
    this.setData({
      showModal: false
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  onLoad: function (option) {
    let that = this;
    app.post("/index/merchant_info", "get", {}).then(res => {
      console.log(res)
      that.tagList(res.merchant.org_type_id)

      that.setData({
        region: [res.merchant.province_name, res.merchant.city_name, res.merchant.area_name]
      })
      that.setData({ pid: res.merchant.org_type_id})
      if (res.merchant.images == null) {
        that.setData({ data: res, imgs: [] })
      } else {
        that.setData({ data: res, imgs: res.merchant.images })
      }
      if (res.merchant.logo){
        that.setData({ img_l: res.merchant.logo })
      }else{
        that.setData({ img_l: res.merchant.wx_avatar })
      }
      if (!res.merchant.extension_tag_ids){
        var arra = res.merchant.extension_tag_ids;
        var arrs = arra.split('');
        that.setData({ extension_tag_ids: arrs })
      }else{
        that.setData({ extension_tag_ids: [] })
      }
      that.setData({
        per_spend: res.merchant.per_spend,
        
        decoration_time: res.merchant.decoration_time,
        near: res.merchant.near,
        detail_address: res.merchant.detail_address,
        business_hours: res.merchant.business_hours,
        regionId: [res.merchant.province_id, res.merchant.city_id, res.merchant.area_id],
        hotel_level: res.merchant.hotel_level,
        decoration_time: res.merchant.decoration_time,
        desc: res.merchant.desc,
        address: res.merchant.lat?'已标注':'',
        longitude: res.merchant.lng,
        latitude: res.merchant.lat,
      })
      console.log(that.data.longitude)
      if (res.merchant.service == null) {
        that.setData({  TipsItems: [] })
      } else {
        that.setData({ TipsItems: res.merchant.service })
      }
      var tags = that.data.data.merchant.extension_tag;
      var arr = that.data.LabelItems;
      for (var i = 0; i < tags.length; i++) {
        for (var n = 0; n < arr.length; n++) {
          if (tags[i].id == arr[n].id) {
            arr[n].state = 1;
            that.data.extension_tag_ids.push(arr[n].id)
          }
        }
      }
      console.log(arr)
      that.setData({ LabelItems: arr })
    });
    // 酒店星级
    app.post("/category/hotel_type","get",{}).then(res =>{
      that.setData({ xingJi:res})
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
   
    
  },
  // 推广标签列表
  tagList(id){
    let that = this;
    app.post("/category/extension_tag", "get", { id:id}).then(res =>{
      res.forEach(function(v,i){
        res[i].state=0;
      })
      that.setData({ LabelItems: res })
      console.log(res)
      var tags = that.data.data.merchant.extension_tag;
      var arr = that.data.LabelItems;
      for (var i = 0; i < tags.length; i++) {
        for (var n = 0; n < arr.length; n++) {
          if (tags[i].id == arr[n].id) {
            arr[n].state = 1;
            that.data.extension_tag_ids.push(arr[n].id)
          }
        }
      }
      console.log(arr)
      that.setData({ LabelItems: arr })
     
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})